<!-- 非法端口 -->
<template>
<div class="dashboard-editor-container">
  <el-row style="background: #fff; padding: 16px;">
    <div style="display:flex;justify-content:space-between;">
        <div >
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addClick()">添加规则</el-button>
        </div>
      </div>
    <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
      <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
      <el-table-column label="规则名称" prop="RuleName" align="left" show-overflow-tooltip width="160px"></el-table-column>
      <el-table-column label="应用对象" show-overflow-tooltip prop="DeviceObj" width="160px" align="left">
        <template slot-scope="{row}">
          <span v-if="row.DeviceObj ==''">全部</span>
          <span v-if="Array.isArray(row.DeviceObj)">{{ row.DeviceObj.join(',') }}</span>
          <span v-else>{{ row.DeviceObj }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="规则生效" show-overflow-tooltip prop="IsValid" align="left" width="160px">
        <template slot-scope="{row}">
           <span style="color:#67C23A" v-if="row.IsValid === 1" type="success">生效</span>
           <span style="color:#F56C6C" v-else type="danger">停用</span>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" show-overflow-tooltip prop="Descp" align="left"></el-table-column>
      <!-- <el-table-column label="定时核查"  show-overflow-tooltip prop="CheckType" align="left">
        <template slot-scope="{row}">
           <span style="color:#67C23A" v-if="row.CheckType === 0" type="success">启用</span>
           <span style="color:#F56C6C" v-else type="danger">禁用</span>
        </template>
      </el-table-column> -->
      <el-table-column label="执行方案"  show-overflow-tooltip prop="ExecuteMode" align="left">
        <template slot-scope="{row}">
           <span  v-if="row.ExecuteMode === 1" type="success">立即执行</span>
           <span  v-else type="danger">用户决策</span>
        </template>
      </el-table-column>
      <el-table-column label="执行频率"  show-overflow-tooltip prop="CheckType" align="left">
        <template slot-scope="{row}">
           <span  v-if="row.CheckType == 0" type="danger">每天</span>
           <span  v-if="row.CheckType == 1" type="danger">每周{{ daysOfWeek(row.DayWeek) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="执行时间"  show-overflow-tooltip prop="CheckType" align="left">
        <template slot-scope="{row}">
           <span  v-if="row.CheckType == 0 " type="danger">{{row.time}}</span>
           <span  v-if="row.CheckType == 1 " type="danger">{{row.time}}</span>
        </template>
      </el-table-column>
      <el-table-column label="核查项目数量" show-overflow-tooltip prop="Descp" align="left">
         <template slot-scope="{row}">
           <span  v-if="row.checkitem[0] == 0" type="danger">{{baselineTable.length}}</span>
           <span  v-else type="danger">{{row.checkitem.length}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="150px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">修改</el-button>
          <el-button size="mini" type="danger" @click="deleteClick(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-row>
  <el-dialog
    top="5vh"
    :close-on-click-modal="false"
    :close-on-press-escape=false
    :title="Action === 1 ? '添加规则' : '修改规则' "
    :visible.sync="dialogVisible"
    v-el-drag-dialog
    width="600px">
      <el-form label-width="130px" :model="accountForm" :rules="rules" ref="accountForm">
        <el-row >
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则名称:' prop="RuleName">
              <el-input v-model.trim="accountForm.RuleName"  :disabled="Action !== 1" :maxlength="300"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则生效:' prop="IsValid">
              <el-switch v-model="accountForm.IsValid" :active-value="1" :inactive-value="0" active-color="#3a8adb" inactive-color="#ccc"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
             <el-form-item label='应用对象:' prop="DeviceObjType">
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="1">全部</el-radio>
              <!-- <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="2">指定校区</el-radio> -->
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="8">指定角色</el-radio>
              <el-radio v-model="accountForm.DeviceObjType" @change="DeviceObjTypeChange" :label="6">指定资产</el-radio>
              <el-select v-model="accountForm.DeviceObj" multiple style="width:100%" :placeholder="accountForm.DeviceObjType==1?'全部':'请选择'" :disabled="accountForm.DeviceObjType === 1">
                <el-option
                  v-for="(item,index) in accountForm.DeviceObjType ===6 ?assetList:DeviceObjList"
                  :key="index"
                  :label="item.DeviceName"
                  :value="item.DeviceName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label="备注信息" prop="Descp">
              <el-input placeholder="请输入备注" type="textarea" :rows="3"  v-model="accountForm.Descp"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='定时核查:' prop="CheckType">
              <el-radio v-model="accountForm.CheckType"   :label="0">启用</el-radio>
              <el-radio v-model="accountForm.CheckType"   :label="2">禁用</el-radio>
            </el-form-item> 
          </el-col> -->
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label="执行频率:" prop="CheckType">
                  <el-radio-group v-model="accountForm.CheckType">
                    <el-radio :label="0" >每天</el-radio>
                    <el-radio :label="1" >每周</el-radio>
                  </el-radio-group>
                </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item v-if="accountForm.CheckType === 0" label="每天:">
                  <el-select v-model="accountForm.dailyHour" style="width: 100px; margin-right: 10px">
                    <el-option v-for="hour in options1" :key="hour" :label="hour" :value="hour"></el-option>
                  </el-select>

                  <span style="margin-right: 10px">时</span>
                  <el-select v-model="accountForm.dailyMinute" style="width: 100px; margin-right: 10px">
                    <el-option v-for="minute in options2" :key="minute" :label="minute" :value="minute"></el-option>
                  </el-select>
                  <span style="margin-right: 10px">分</span>
                </el-form-item>

            <el-form-item v-if="accountForm.CheckType === 1" label="每周:">
                  <el-select v-model="accountForm.weeklyDay" style="width: 100px; margin-right: 10px">
                    <el-option label="星期一" value="1"></el-option>
                    <el-option label="星期二" value="2"></el-option>
                    <el-option label="星期三" value="3"></el-option>
                    <el-option label="星期四" value="4"></el-option>
                    <el-option label="星期五" value="5"></el-option>
                    <el-option label="星期六" value="6"></el-option>
                    <el-option label="星期日" value="0"></el-option>
                  </el-select>
                  <el-select v-model="accountForm.dailyHour" style="width: 100px; margin-right: 10px">
                    <el-option v-for="hour in options1" :key="hour" :label="hour" :value="hour"></el-option>
                  </el-select>

                  <span style="margin-right: 10px">时</span>
                  <el-select v-model="accountForm.dailyMinute" style="width: 100px; margin-right: 10px">
                    <el-option v-for="minute in options2" :key="minute" :label="minute" :value="minute"></el-option>
                  </el-select>
                  <span style="margin-right: 10px">分</span>
                </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='执行方案:' prop="ExecuteMode">
              <el-radio v-model="accountForm.ExecuteMode"   :label="1">立即执行</el-radio>
              <el-radio v-model="accountForm.ExecuteMode"   :label="2">用户决策</el-radio>
            </el-form-item> 
          </el-col>
           <el-col :xs="19" :sm="19" :lg="19">
            <el-form-item label='核查指定项目:' prop="screenTime">
              <el-button type="primary" @click="changeModel()">选择核查项目</el-button>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="5" :lg="5" style="margin-top:10px;">
            <span style="color:#aaa;">
              （默认全部核查）
            </span>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            
            <el-form-item label='核查项目:' prop="screenTime">
            
              <el-input type="textarea"   :autosize="{ minRows: 1, maxRows: 3}" resize="none" v-model="selectInfo" disabled />
          </el-form-item>
          </el-col>
        </el-row>
      </el-form> 
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
    top="5vh"
    :close-on-click-modal="false"
    :close-on-press-escape=false
    title="核查指定项目"
    :visible.sync="dialogObjVisible"
    v-el-drag-dialog
    width="600px">
      <el-table ref="multipleTable" stripe border :data="baselineTable" style="width: 100%; margin-top: 15px" height="440px" @selection-change="handleSelectionChange">
        <el-table-column label="序号" width="60" type="index" prop="id"></el-table-column>
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column label="核查项目" show-overflow-tooltip prop="Subject" align="left"></el-table-column>
      </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="checkData">确 定</el-button>
        </span>
    </el-dialog>
</div>
</template>

<script>
import { connrequest } from '@/api/firstPage'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
directives: { elDragDialog },
data() {
return {
  pageNum: 1,
  pageSize: 10,
  tableData: [],
  RoleList: [],
  assetList:[],
  Action: 1,
  dialogVisible: false,
  dialogObjVisible: false,
  accountForm: {
  },
  DeviceObjList: [],
  rules: {
    RuleName: [
      { required: true, message: "请输入规则名称"}
    ],
  },
  selectInfo:'',
  options1: [],
  options2: [],
  baselineTable: [],
  multipleSelection: [],
  checkitem:[],
  example:[],
}
},
//生命周期 - 创建完成（访问当前this实例）
created() {
  for (let hour = 0; hour < 24; hour++) {
      if (hour < 10) hour = "0" + hour;
      else hour = String(hour);
      this.options1.push(hour);
    }
    for (let hour = 0; hour < 60; hour++) { 
      if (hour < 10) hour = "0" + hour;
      else hour = String(hour);
      this.options2.push(hour); 
    }
  this.getData()
  this.CenterGetDevice()
},
//生命周期 - 挂载完成（访问DOM元素）
mounted() {

},
methods: {
   daysOfWeek(dayIndex) {
    const days = [ '日','一', '二', '三', '四', '五', '六'];
    return days[dayIndex];
    },
   // 获取选择了哪些
  handleSelectionChange(val) {
    this.multipleSelection = val
  },
  async getData(){
    // GetListenPortRule
    const res = await connrequest("GetBaseLineCheck");
    res.Data = res.Data || [];
    res.Data.forEach(item=>{
      // item.CheckType = item.CheckType != 2 ? 0 : item.CheckType || 0;
      // item.CheckType = item.CheckType !== 2 ? 0 : item.CheckType || 0;
      item.time = item.time || "00:00";
      item.dailyHour = item.time.slice(0, 2);
      item.dailyMinute = item.time.slice(3);
      if (item.DayWeek == undefined) item.DayWeek = "1";
      item.weeklyDay =
        item.DayWeek === 7 ? "1" : String(item.DayWeek);
      item.checkitem = item.checkitem || [0] 
    })
    this.tableData = res.Data
    const resD = await connrequest("GetBaselineFixSet");
    this.baselineTable = resD.Data.BaselineResult;
    
  },
  async CenterGetDevice(){
    const data = {
      Paging:{
        QueryPageNo: 1,
        QueryPageLength: 100000000
      },
      Filter:{
        Status: 0,
      }
    }
    const res = await connrequest('CenterGetDevice', data)
    this.assetList = res.Data
  },
  checkData(){
      this.dialogObjVisible= false
      this.checkitem =  this.getItemid(this.multipleSelection)
      this.accountForm.checkitem = this.checkitem
      return 
    },
    getItemid(table){
      this.selectInfo = ''
      if(table.length == this.baselineTable.length)
      {
        this.selectInfo = '全部核查'
        return [0]
      }
      var val = []
      table.forEach(item =>{
        this.selectInfo += item.Subject + "、"
        val.push(parseInt(item.id))
      })
      this.selectInfo = this.selectInfo.slice(0, -1)
      val.sort((a, b) => a - b);
      return val
    },
    changeModel(){
    this.dialogObjVisible = true
    this.GetBaselineFixSet();
  },
  async GetBaselineFixSet() {
      const res = await connrequest("GetBaselineFixSet");
      this.baselineTable = res.Data.BaselineResult;
      if(this.accountForm.checkitem[0] == 0)
        this.selectAllRows()
      else
      {
        this.checkitem = this.accountForm.checkitem
        this.selectItemRows()
      }
    },
    // isDisabled(){
    //   if(this.accountForm.CheckType === 2)
    //     return 0
    //   else
    //     return 1
    // },
    selectAllRows() {
      if (this.$refs.multipleTable) {
        // 选择所有行
        this.$nextTick(() => {
          this.$refs.multipleTable.toggleAllSelection(); // 手动选中所有行
        });
        
      } 
    },
    selectItemRows(){
      // 选择指定行
      this.$nextTick(() => {
        this.checkitem.forEach(index => {
          this.$refs.multipleTable.toggleRowSelection(this.baselineTable[index-1], true);
        });
      });
    },
  async DeviceObjTypeChange(value){
    this.$set(this.accountForm, 'DeviceObj', '')
    if(value === 1){
      this.DeviceObjList = []
    }else if(value === 2){
      const res = await this.GetSchoolStatusSumTree()
      this.DeviceObjList = [res]
    }else if(value === 8){
      const res = await this.GetRolestatus()
      var arr = []
      res.map(item => {
        var val ={'DeviceName': item.Role}
        arr.push(val)
      })
      this.DeviceObjList = arr
    }else{
      const res = await this.GetDeviceStatusSumTree()
      this.DeviceObjList = [res]
      console.log(this.DeviceObjList);
    }
  },
  // 获取校区树
  async GetSchoolStatusSumTree() {
    const res = await connrequest('GetSchoolStatusSumTree')
    return this.transformData(res.Data)
  },
  // 获取角色
  async GetRolestatus() {
    const res = await connrequest('GetParamDictRole')
    return res.Data
  },
  // 获取资产树
  async GetDeviceStatusSumTree() {
    const res = await connrequest('GetDeviceStatusSumTree')
    return this.transformData(res.Data)
  },
  transformData(inputData) {
    const { RootName, PrimArea} = inputData;
      return {
        SubClass: RootName,
        value: RootName,
        level: 1,
        children: PrimArea.map(area => ({
          SubClass: area.PrimAreaName,
          value: area.PrimAreaName,
          level: 2,
          children: area.SecondArea.map(secondArea => ({
            SubClass: secondArea.SecondAreaName,
            value: secondArea.SecondAreaName,
            level: 3,
        }))
      }))
    }
  },
  handleChange(row){
    // console.log(row);
  },
  // 获取子节点的校区
  async lazyLoad(node, resolve){
    if(node.level < 3){
      resolve(node.data) 
    }else{
      const data = {
        Paging:{ 
          QueryPageNo: 1,
          QueryPageLength: 100000
        },
        Filter:{
          SecondArea: node.label,
        }
      }
      const res = await connrequest('GetSchool', data)
      let arr = []
      res.Data.map(item => {
        arr.push( {SubClass: item.SchoolName, value: item.SchoolName, level: 4, children: undefined} )
      })
      resolve(arr) 
    }
  },
  // 获取子节点的资产
  async lazyLoad2(node, resolve){
    if(node.level < 3){
      resolve(node.data) 
    }else{
      const data = {
        Paging:{
          QueryPageNo: 1,
          QueryPageLength: 100000
        },
        Filter:{
          SecondArea: node.label,
        }
      }
      const res = await connrequest('CenterGetDevice', data)
      let arr = []
      res.Data.map(item => {
        arr.push( {SubClass: item.DeviceName, value: item.DeviceName, level: 4, children: undefined} )
      })
      resolve(arr) 
    }
  },
 addClick() {
    this.Action = 1;
    this.selectInfo =''
    this.$nextTick(() => {
      // 等待组件挂载
      if (this.$refs['accountForm']) {
        this.accountForm = {
          IsValid: 1,
          DeviceObjType: 1,
          dailyHour: "00",
          dailyMinute: "00",
          CheckType: 0,
          weeklyDay: "1",
          ExecuteMode:1,
          DeviceObj: [],
          checkitem: [0]
        };
        this.$refs['accountForm'].resetFields();
      } else {
        // console.error('Error: $refs["accountForm"] is still undefined.');
        this.accountForm = {
        IsValid: 1, 
        DeviceObjType: 1,
        dailyHour: "00",
        dailyMinute: "00",
        CheckType: 0,
        weeklyDay: "1",
        ExecuteMode:1,
        DeviceObj: [],
        checkitem: [0]
      };
      }
      this.selectDetail()
      this.dialogVisible = true;
    });
  },
  changeClick(row, index){
    // console.log(row);
    this.Action = 2
    this.$nextTick(()=>{
      this.accountForm = {...row}
      this.$refs['accountForm'].resetFields();
      this.selectDetail()
    })
    this.dialogVisible = true
  },
  selectDetail(){
    this.selectInfo = ''
    this.accountForm.checkitem.forEach(item=>{
      if(item == 0)
      {
          this.selectInfo += '全部核查'
          return
      }
      else
      {
          this.selectInfo += this.baselineTable[item-1].Subject + "、"
      }
    })
    if(this.selectInfo != '全部核查')
      this.selectInfo = this.selectInfo.slice(0, -1)
  },
  deleteClick(row){
    this.$confirm('此操作将永久删除该规则, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      let data = {
        Data: {
          Action: 3,
          Detail: {...row}
        }
      }
      const res = await connrequest('EditBaseLineCheck', data)
      if(res.Status.StatusCode === 0){
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.getData()
        this.dialogVisible = false
      }
    }).catch(() => {
      this.$message({
        type: 'info',
        message: '已取消删除'
      });          
    });
  },
  submit(){
    // this.checkitem = 
    // return
    // var time = this.accountForm.dailyHour + ":" + this.accountForm.dailyMinute;
      let data = {};
    this.$refs['accountForm'].validate( async(valid) => {
      
      if(valid){
        if(this.accountForm.DeviceObjType === 2){
          if(!this.accountForm.DeviceObj) {
            this.$message.error('请选择校区')
            return false
          }
        }
        if(this.accountForm.DeviceObjType === 8){
          if(!this.accountForm.DeviceObj) {
            this.$message.error('请选择角色')
            return false
          }
        }
        if(this.accountForm.DeviceObjType === 6){
          if(!this.accountForm.DeviceObj) {
            this.$message.error('请选择资产')
            return false
          }
        }
        const time = `${this.accountForm.dailyHour}:${this.accountForm.dailyMinute}`;
        const datas = {
          Data: {
            // CheckType: this.accountForm.CheckType === 2 ? this.accountForm.CheckType : this.accountForm.CheckType,
            time,
            DayWeek: this.accountForm.CheckType === 0 ? 7 : parseInt(this.accountForm.weeklyDay),
            checkitem: this.accountForm.checkitem.length === 0 ? [0] : this.accountForm.checkitem
          },
        };
        // if (this.accountForm.CheckType === 2) {
        //   datas.Data.checkitem = [0]; // Set default checkitem when CheckType is 2
        // }
        this.accountForm = {
          ...this.accountForm,
          ...datas.Data
        }
        delete this.accountForm.dailyHour
        delete this.accountForm.dailyMinute
        delete this.accountForm.weeklyDay
      let data = {
        Data: {
        Action: this.Action,
        Detail:{...this.accountForm}     
        }
      }
    try {
      const res = await connrequest('EditBaseLineCheck', data)
        if(res.Status.StatusCode === 0){
          this.$message.success(this.Action === 1 ? '添加成功' : '修改成功')
          this.getData()
          this.dialogVisible = false
        }
    } catch (error) {
          this.accountForm = {
            dailyHour: "00",
            dailyMinute: "00",
            weeklyDay: "1",
            ...this.accountForm
          };
      }
     }
  })
  },
}
}
</script>
<style scoped>
/* @import url(); 引入css类 */
.el-dialog__title::before {
  padding-left: 30px; /* 调整标题和图标的距离 */
  background-image: url('../../assets/logo.png'); /* 指定图标路径 */
  background-repeat: no-repeat; /* 防止背景图片重复 */
  background-position: left center; /* 将图标放在标题左侧中间 */ 
}

</style>